import sys
from docx import Document
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                             QPushButton, QLabel, QFileDialog, QListWidget, 
                             QProgressBar, QMessageBox)

class WordLineReplacer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle('Word文档空行替换工具')
        self.setGeometry(300, 300, 500, 400)
        
        # 主部件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        layout = QVBoxLayout()
        
        # 标题
        title_label = QLabel('智能空行替换工具（连续空行→单个#######）')
        title_label.setStyleSheet('font-size: 16px; font-weight: bold;')
        layout.addWidget(title_label)
        
        # 选择文件按钮
        self.select_btn = QPushButton('选择Word文件')
        self.select_btn.clicked.connect(self.select_files)
        layout.addWidget(self.select_btn)
        
        # 文件列表
        self.file_list = QListWidget()
        layout.addWidget(self.file_list)
        
        # 处理按钮
        self.process_btn = QPushButton('处理选中文件')
        self.process_btn.clicked.connect(self.process_files)
        self.process_btn.setEnabled(False)
        layout.addWidget(self.process_btn)
        
        # 进度条
        self.progress = QProgressBar()
        layout.addWidget(self.progress)
        
        # 状态标签
        self.status_label = QLabel('准备就绪')
        layout.addWidget(self.status_label)
        
        main_widget.setLayout(layout)
        
    def select_files(self):
        options = QFileDialog.Options()
        files, _ = QFileDialog.getOpenFileNames(
            self, "选择Word文档", "", 
            "Word Files (*.docx);;All Files (*)", 
            options=options)
        
        if files:
            self.file_list.clear()
            self.file_list.addItems(files)
            self.process_btn.setEnabled(True)
            self.status_label.setText(f'已选择 {len(files)} 个文件')
    
    def process_files(self):
        files = [self.file_list.item(i).text() for i in range(self.file_list.count())]
        
        if not files:
            QMessageBox.warning(self, '警告', '没有选择任何文件!')
            return
            
        self.progress.setMaximum(len(files))
        self.progress.setValue(0)
        
        success_count = 0
        
        for i, file_path in enumerate(files):
            try:
                self.status_label.setText(f'正在处理: {file_path}')
                QApplication.processEvents()
                
                doc = Document(file_path)
                new_paragraphs = []
                
                for para in doc.paragraphs:
                    current_text = para.text
                    
                    # 如果不是空行，直接保留
                    if current_text.strip():
                        new_paragraphs.append(current_text)
                    else:
                        # 是空行，检查前一个段落
                        if new_paragraphs and new_paragraphs[-1] == '#######':
                            # 前一段是#######，跳过当前空行（相当于删除）
                            continue
                        else:
                            # 前一段不是#######，替换为#######
                            new_paragraphs.append('#######')
                
                # 重建文档
                doc.paragraphs.clear()
                for text in new_paragraphs:
                    doc.add_paragraph(text)
                
                new_path = file_path.replace('.docx', '_modified.docx')
                doc.save(new_path)
                success_count += 1
                
            except Exception as e:
                self.status_label.setText(f'处理 {file_path} 时出错: {str(e)}')
            finally:
                self.progress.setValue(i + 1)
        
        self.status_label.setText(f'处理完成! 成功处理 {success_count}/{len(files)} 个文件')
        QMessageBox.information(self, '完成', f'成功处理 {success_count} 个文件')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = WordLineReplacer()
    ex.show()
    sys.exit(app.exec_())